package com.atguigu.consumer;

import com.alibaba.fastjson.JSON;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.feign.PaymentFeignClient;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;


/**
 * @author ：Hachimen
 * @date ：Created in 2021/9/8 18:49
 * @description：订单过期MQ消费者类
 * @modified By：
 * @version:
 */
@Component
public class OrderConsumer {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentFeignClient paymentFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //取消订单的监视器(超时未支付取消订单
    @RabbitListener(queues = MqConst.CANCEL_ORDER_QUEUE)
    public void cancelOrder(Long orderId, Message message, Channel channel) throws IOException {
        RetVal retVal = paymentFeignClient.queryAlipayTradeStatus(orderId);
        if(!retVal.isOk()||!"TRADE_SUCCESS".equals(retVal.getData())){//如果支付成功则不取消
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            //如果订单未支付则关闭订单
            if(orderInfo!=null&&orderInfo.getOrderStatus().equals(ProcessStatus.UNPAID.name())){
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.CLOSED);
                PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                //如果支付订单为未支付则关闭支付订单
                if(paymentInfo!= null&&paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
                    //发消息关闭支付订单
                    rabbitTemplate.convertAndSend(MqConst.CLOSE_PAYMENT_EXCHANGE,MqConst.CLOSE_PAYMENT_ROUTE_KEY,orderId);
                    //如果支付宝订单为未支付，关闭支付宝订单
                    if(!paymentFeignClient.queryAlipayTrade(orderId)){
                        paymentFeignClient.closeAlipayTrade(orderId);
                    }
                }
            }
        }



        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    //支付成功之后修改订单状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.PAY_ORDER_QUEUE,durable = "false"),
            exchange = @Exchange(value = MqConst.PAY_ORDER_EXCHANGE,durable = "false"),
            key = {MqConst.PAY_ORDER_ROUTE_KEY}))
    public void updateOrderAfterSuccess(Long orderId, Message message, Channel channel) throws IOException {
        if (orderId != null){
            OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
            if(orderInfo!=null&& orderInfo.getProcessStatus().equals(ProcessStatus.UNPAID.name()))
            orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.PAID);
            //发消息改库存
            orderInfoService.sendMsgToWarehouse(orderInfo);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    //减库存之后修改订单状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.SUCCESS_DECREASE_STOCK_QUEUE,durable = "false"),
            exchange = @Exchange(value = MqConst.SUCCESS_DECREASE_STOCK_EXCHANGE,durable = "false"),
            key = {MqConst.SUCCESS_DECREASE_STOCK_ROUTE_KEY}))
    public void updateOrderAfterDecrease(String jsonString, Message message, Channel channel) throws IOException {
        if(!StringUtils.isEmpty(jsonString)){
            Map map = JSON.parseObject(jsonString, Map.class);
            String orderId = (String)map.get("orderId");
            String status = (String)map.get("status");
            OrderInfo orderInfo = orderInfoService.getOrderInfo(Long.parseLong(orderId));
            if("DEDUCTED".equals(status)){
                //减库存成功
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.WAITING_DELEVER);
            }else{
                //超卖
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
